/*eslint-disable*/
// 批量任务脚本
const fs = require('fs')
const path = require('path')
const createHtmlDom = require('htmldom')

let dir = path.resolve(path.dirname(__dirname) + '/pages/')

let htmlList = getAllFileList(dir).compileFiles

htmlList.forEach(item => {
  let htmlStr = fs.readFileSync(item, { encoding: 'utf-8' })

  let $ = createHtmlDom(htmlStr)
  //批量任务一： 每个html在head中增加icon

  //如果已有link标签，则插入在所有links标签之前
  //如果没有link标签，则插入在所有styles标签之前
  //如果都没有，则插入在Head标签末尾

  let links = $('link')
  let styles = $('style')
  let metas = $('meta')

  let appendLink =
    '<link rel="shortcut icon" href="./imgs/default-avatar.png" type="image/png" />\n'

  if (links.length) {
    $(links[0]).before(appendLink)
  } else if (styles.length) {
    $(styles[0]).before(appendLink)
  } else {
    $('head').append(appendLink)
  }

  //批量任务二： 每个html在head中增加meta标签
  //<meta name="format-detection" content="telephone=no,address=no,email=no">

  let appendMeta =
    '<meta name="format-detection" content="telephone=no,address=no,email=no"/>\n'

  if (metas.length) {
    $(metas[0]).before(appendMeta)
  } else {
    $('head').prepend(appendMeta)
  }

  //将处理好后的文件写回去
  fs.writeFileSync(item, $('html').outerHTML())
})

function readFileList(path, filesList) {
  let files = fs.readdirSync(path)

  files.forEach(function(itm, index) {
    let stat = fs.statSync(path + itm)
    if (stat.isDirectory()) {
      //递归读取文件
      readFileList(path + itm + '/', filesList)
    } else {
      let obj = {} //定义一个对象存放文件的路径和名字
      obj.path = path //路径
      obj.filename = itm //名字
      filesList.push(obj)
    }
  })
}

//获取文件夹下的所有文件
function getFileList(path) {
  let filesList = []
  path = path.endsWith('/') ? path : path + '/'
  readFileList(path, filesList)
  return filesList
}
//获取指定目录下所有文件
function getAllFileList(opath) {
  let files = {
    compileFiles: [], //获取需要编译的文件
    otherFiles: [] //其他文件
  }

  getFileList(opath).forEach(item => {
    if (['.html'].includes(path.extname(item.filename))) {
      files.compileFiles.push(item.path + item.filename)
    } else {
      files.otherFiles.push(item.path + item.filename)
    }
  })
  return files
}
